<template>
	<view class="test-container">
		<uni-section title="车辆信息" type="line">
			<view class="base-form">
				<view class="base-form-item">车架号：
					<span class="base-form-item-value">{{ baseInfo.vin }}</span>
				</view>
				<view class="base-form-item">车型：
					<span class="base-form-item-value">{{ baseInfo.hpzl }}</span>
				</view>
				<view class="base-form-item">车牌号：
					<span class="base-form-item-value">{{ baseInfo.hphm }}</span>
				</view>
				<view class="base-form-item">里程表：
					<sapn class="base-form-item-value">{{ baseInfo.lCb }}</sapn>
				</view>
			</view>
		</uni-section>

		<uni-section title="全车外观图（一次性最多9张）" type="line">
			<view style="padding: 0 20rpx;">
				<up-upload :fileList="fileListAllCar" @afterRead="afterRead($event, 'allCar')"
					@delete="deletePic($event, 'allCar')" name="allCar" multiple :maxCount="1000"
					:previewFullImage="true"></up-upload>
			</view>
		</uni-section>

		<uni-section title="出厂铭牌（一次性最多9张）" type="line">
			<view style="padding: 0 20rpx;">
				<up-upload :fileList="fileListLeave" @afterRead="afterRead($event, 'leave')"
					@delete="deletePic($event, 'leave')" name="leave" multiple :maxCount="1000"
					:previewFullImage="true"></up-upload>
			</view>
		</uni-section>

		<uni-section title="整备名称（一次性最多9张）" type="line">
			<view style="padding: 0 20rpx;">
				<uni-easyinput v-model="toponym" placeholder="请输入整备部位图片" style="margin-bottom: 20rpx;" />
				<up-upload :fileList="fileListNameplate" @afterRead="afterRead($event, 'name')"
					@delete="deletePic($event, 'name')" name="name" multiple :maxCount="1000" :previewFullImage="true">
				</up-upload>
			</view>
		</uni-section>


		<view class="btns">
			<view class="bnts-audit">
				<view class="item reject" @click="reject">
					驳回到检测
				</view>
				<view class="item insc" @click="insc">
					驳回到采购
				</view>
				<view class="item party" @click="party">
					整备完成
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import {
	getVehcileIdOne,
	updateCarStatus,
	getVehicleJCPhoto,
	getVehcileIdListVehiclePhoto,
	addFileZB,
	deleteVehiclePhoto
} from '@/api/app.js'
export default {
	data() {
		return {
			baseInfo: {},
			toponym: '',
			id: '',
			fileListAllCar: [],
			fileListLeave: [],
			fileListNameplate: [],
		}
	},
	onLoad(opt) {
		if (opt.id) {
			this.id = opt.id
			this.getVehcileIdOne()
			this.getVehicleJCPhoto()
		}
	},
	methods: {
		async afterRead(file, type) {
			console.log(file, type);
			const files = file.file
			const nameMaps = {
				'allCar': '全车外观图',
				'leave': '出厂铭牌',
				'name': this.toponym
			}

			const name = nameMaps[type]
			// 显示加载提示
			uni.showLoading({
				title: '上传中...',
				mask: true
			})

			try {
				// 创建上传任务数组
				const uploadTasks = files.map(item => {
					return new Promise((resolve, reject) => {
						uni.uploadFile({
							url: 'https://api.weijiashangejiance.com/api/VehiclePhoto/Upload2', //仅为示例，非真实的接口地址
							filePath: item.url,
							name: 'file',
							formData: {
								user: 'test'
							},
							success: (uploadFileRes) => {
								try {
									const resp = JSON.parse(uploadFileRes.data)
									if (resp.code === 1) {
										const key = Object.keys(resp.data)[0]
										const value = resp.data[key]
										resolve({
											path: value,
											url: key,
											status: false,
											MemId: uni.getStorageSync('id'),
											vehicleInfoId: this.id,
											name
										})
									} else {
										reject(new Error('上传失败: ' + resp.msg))
									}
								} catch (e) {
									reject(new Error('解析响应失败'))
								}
							},
							fail: (err) => {
								console.log('上传失败', err)
								reject(err)
							}
						})
					})
				})

				// 等待所有上传任务完成
				const uploadResults = await Promise.all(uploadTasks)


				uploadResults.map(async item => {
					// 批量添加文件信息
					const add = await addFileZB(item)
					if (add.code === 1) {
						// 重新获取图片列表
						await this.getVehicleJCPhoto()
						uni.showToast({
							title: '上传成功',
							icon: 'success'
						})
					} else {
						throw new Error('添加文件信息失败')
					}
				})


			} catch (error) {
				console.error('上传过程发生错误:', error)
				uni.showToast({
					title: '上传失败，请重试',
					icon: 'none'
				})
			} finally {
				// 隐藏加载提示
				uni.hideLoading()
			}
		},
		async deletePic(file, type) {
			console.log(file, type);

			// 检查 file 是否存在
			if (file) {
				// 显示加载提示
				uni.showLoading({
					title: '删除中...',
					mask: true
				});

				try {
					// 根据 type 获取对应的文件列表
					let fileList = [];
					switch (type) {
						case 'allCar':
							fileList = this.fileListAllCar;
							break;
						case 'leave':
							fileList = this.fileListLeave;
							break;
						case 'name':
							fileList = this.fileListNameplate;
							break;
						default:
							throw new Error('未知的文件类型');
					}

					// 检查索引是否合法
					if (file.index >= 0 && file.index < fileList.length) {
						const item = fileList[file.index];
						// 调用删除接口
						deleteVehiclePhoto(item).then(() => {
							setTimeout(async () => {
								// 重新获取图片列表
								await this.getVehicleJCPhoto();
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
							}, 100)
						})

					} else {
						throw new Error('无效的文件索引');
					}
				} catch (error) {
					console.error('删除过程发生错误:', error);
					uni.showToast({
						title: '删除失败，请重试',
						icon: 'none'
					});
				} finally {
					// 隐藏加载提示
					uni.hideLoading();
				}
			}
		},
		// 车辆信息
		async getVehcileIdOne() {
			const res = await getVehcileIdOne({
				id: this.id
			})
			if (res.code === 1) {
				this.baseInfo = res.data
			}
		},
		// 车辆图片
		// 车辆图片
		async getVehicleJCPhoto() {
			console.log('获取车辆图片');

			const res = await getVehcileIdListVehiclePhoto({
				id: this.id
			})
			if (res.data) {
				const imgList = res.data.map((item) => {
					return {
						type: 'image', // 文件类型，image/video/file
						...item,
						url: 'http://www.weijiashangejiance.com' + item.url
					}
				})

				this.fileListAllCar = imgList.filter((item) => item.name === '全车外观图')
				this.fileListLeave = imgList.filter((item) => item.name === '出厂铭牌')
				this.fileListNameplate = imgList.filter((item) => item.name !== '全车外观图' && item.name !== '出厂铭牌')
			}

		},
		handleEdit() {
			delete this.baseInfo.vehicleJCPhotos;
			delete this.baseInfo.vehiclePhotos;
			delete this.baseInfo.infoFiles;
			this.baseInfo.isJC = false;
			this.baseInfo.jcId = 0;
			this.baseInfo.isDel = true;
			this.baseInfo.isZb = false;
			this.baseInfo.zbId = 0;
		},
		// 驳回车辆
		reject() {
			uni.showModal({
				title: '提示',
				content: '确定驳回车辆吗？',
				success: async (res) => {
					if (res.confirm) {
						this.handleEdit();
						const resp = await updateCarStatus(this.baseInfo)
						if (resp.code === 1) {
							uni.navigateBack()
						}

					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		},
		insc() {
			uni.showModal({
				title: '提示',
				content: '确定内检完成吗？',
				success: async (res) => {
					if (res.confirm) {
						this.handleEdit();
						this.baseInfo.jyxm = "内检";
						const resp = await updateCarStatus(this.baseInfo)
						if (resp.code === 1) {
							uni.navigateBack()
						}
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		},
		party() {
			uni.showModal({
				title: '提示',
				content: '确定第三方检测完成吗？',
				success: async (res) => {
					if (res.confirm) {
						this.handleEdit()
						this.baseInfo.isJC = true;
						this.baseInfo.jcId = uni.getStorageSync('id');
						const resp = await updateCarStatus(this.baseInfo)
						if (resp.code === 1) {
							uni.navigateBack()
						}
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		},
	}
}
</script>

<style scoped lang="scss">
.test-container {
	padding: 20rpx 20rpx 130rpx;

	.base-form {
		padding: 0 20rpx 20rpx;

		.base-form-item {
			font-size: 26rpx;
			font-weight: bold;
			line-height: 50rpx;

			.base-form-item-value {
				font-size: 24rpx;
			}
		}
	}

	.btns {
		position: fixed;
		bottom: 30rpx;
		left: 0;
		width: 100%;
		z-index: 100;

		.bnts-audit {
			display: flex;
			align-items: center;
			justify-content: space-around;
			padding: 0 30rpx;

			.item {
				flex: 1;
				text-align: center;
				color: #ffffff;
				padding: 20rpx 0;
				border-radius: 13rpx;
			}

			.reject {
				background-color: #f56c6c;
			}

			.insc {
				margin: 0 30rpx;
				background-color: #07c160;
			}

			.party {
				background-color: #1989fa;
			}
		}
	}

	.file-name {
		display: inline-block;
		width: 150rpx;
		text-align: center;
		margin-right: 10rpx;
	}
}
</style>